var hot1;
var data1 = (function() {
	var result = [];
	for (var row = 0; row < 20; row++) {
		var lines = [];
		for (var col = 0; col < 15; col++) {
			lines.push('');
		}
		result.push(lines);
	}
	return result;
})();


function showDbFunDialog(startRow, startCol) {
	var open = function() {
		var cellMeta = hot1.getCellMeta(startRow, startCol);
		var code = cellMeta.code;
		var backType = cellMeta.backtype;
		// 设置脚本
		$('#setVal', this).val(code);
		$('#freeDataPreview').parent().hide();
		$('#setPoints', this).val('');

		if (backType) {
			$('input[name="backType"][value="' + backType + '"]', this).prop('checked', true).trigger('change');
			if (backType == 'table') {
				$('#setPoints', this).val(cellMeta.points);
			}
		} else {
			$('input[name="backType"]:first', this).prop('checked', true).trigger('change');
		}
		$(this).css('z-index', 1000);
		$('.ui-widget-overlay:last').css('z-index', 1000);
	};
	var ok = function() {
		var $_setVal = $('#setVal', this);
		$_setVal.focus();
		var val = $_setVal.val();
		var backType = $('input[name="backType"]:checked', this);

		if (val) {
			var cellMeta = hot1.getCellMeta(startRow, startCol);
			cellMeta.renderer = coverRenderer;

			cellMeta.code = val;
			cellMeta.backtype = backType.val();
			if (cellMeta.backtype == 'table') {
				cellMeta.points = $('#setPoints', this).val();
			}
			var classNames = cellMeta.className;
			var defClassName = hot1.getSettings().className;
			if (classNames.indexOf('dbFun') == -1) {
				cellMeta.className = defClassName + ' dbFun';
			}
			cellMeta.readOnly = true;

			$(this).dialog("close");
			hot1.render();
		} else {
			alert('脚本不能为空');
		}
	}

	$('#freeTabSetVal').dialog({
		title: '设置值',
		width: 600,
		modal: true,
		show: true,
		resizable: false,
		open: open,
		buttons: [{
			text: "确定",
			click: ok
		}, {
			text: "取消",
			click: function() {
				$(this).dialog("close");
			}
		}]
	});
}
var hotSetting = {
	contextMenu: {
		callback: function(key, options) {
			var startCol = options.start.col,
				startRow = options.start.row;
			if (key === 'setVal') {
				var cellMeta = this.getCellMeta(startRow, startCol);
				cellMeta.readOnly = true;
				setTimeout(function() {
					showDbFunDialog(startRow, startCol);
				}, 100);
			}
		},
		items: {
			"row_above": {
				name: '向上插入一行'
			},
			"row_below": {
				name: '向下插入一行'
			},
			"hsep1": "---------",
			"col_left": {
				name: '左侧插入一列'
			},
			"col_right": {
				name: '右侧插入一列'
			},
			"hsep2": "---------",
			"remove_row": {
				name: '删除行'
			},
			"remove_col": {
				name: '删除列'
			},
			"hsep3": "---------",
			"alignment": {
				name: '对齐'
			},
			"hsep4": "---------",
			"mergeCells": {
				name: '合并单元格'
			},
			"hsep5": "---------",
			"setVal": {
				name: '设置动态值'
			}
		}
	}
};

function insertCkFreeTableHtml(showHtml, hideHtml, insertEle, simpleUseArgs) {
	$('#expressionDiv').children().remove();
	var showTable = $(showHtml);
	var expressions = [];
	// 获得表格宽度
	var tableWidth = $('body', CKEDITOR.instances.editor.document.$).width();

	var tdCount = 0;
	showTable.find('tr').each(function(trIndex, tr) {
		var $_tr = $(tr);
		var offSetCode = 0;
		$_tr.find('td:not(.delspan)').each(function(tdIndex, td) {
			var $_td = $(td);
			if ($_td.data('type') == 'bottom') {
				offSetCode += $_td.data('col');
			}
			var colName = String.fromCharCode(65 + tdIndex + offSetCode);
			if (trIndex == 0) {
				tdCount++;
			}
			if ($_td.data('type') == 'head') {
				offSetCode += $_td.data('col');
			}
			if ($_td.hasClass('sysFun')) {
				var sysVal = $_td.text();
				var isFind = false;
				for (var i = 0; i < simpleUseArgs.length; i++) {
					var useArg = simpleUseArgs[i];
					var argName = '#' + useArg.name;
					// 找到关键字
					if (sysVal.indexOf(argName) >= -1) {
						var sysArr = sysVal.split(argName);
						sysVal = sysArr.join(useArg.val);
						isFind = true;
					}
				}
				$_td.text(sysVal);
			}
			var val = $(td).text();
			$_td.attr('id', colName + (trIndex + 1))
			if (val) {
				$_td.attr('value', val);
			}
			if ($_td.hasClass('expression')) {
				expressions.push($(td));
			}
		});
		if (trIndex == 0) {
			tdCount += offSetCode;
		}
	});
	if (tdCount > 0) {
		// 重新指定表格宽度
		var realWidth = tdCount * 60;
		insertEle.setStyle('width', '99%');
		insertEle.setStyle('overflow-x', 'auto');
		if (tableWidth < realWidth) {
			showTable.css('width', realWidth + 'px');
		}
	}

	$('#expressionDiv').append(showTable);
	var inputObj = document.querySelector('#expressionDiv');
	var rules = new ruleJS('expressionDiv');
	rules.init();
	for (var index in expressions) {
		var expression = expressions[index];
		var formula = expression.attr('code').substr(1);
		var parsed = rules.parse(formula, inputObj);
		var error = parsed.error;
		var result = error ? '-' : parsed.result;
		expression.text(result);
	}

	insertEle.appendHtml('<br/>' + showTable[0].outerHTML);
	insertEle.appendHtml(hideHtml);
	var areaHeight = $('html', CKEDITOR.instances.editor.document.$).height();
	var realHeight = $('#cke_1_contents').height();
	if (realHeight < areaHeight) {
		$('#cke_1_contents').height(areaHeight + 50);
	}
}

Function.prototype.getName = function() {
	return this.name || this.toString().match(/function\s*([^(]*)\(/)[1]
}


$(document).ready(function() {
	function preview(type, code) {
		function doSome(data) {
			var tmpData = [];
			if (type == 'signValue') {
				tmpData.push(['单列值']);
				tmpData.push([data]);
			} else if (type == 'smartParam') {
				headName = '参数值';
				tmpData.push(['参数值']);
				tmpData.push([SimpleDataHandler.getSmartParamName(code, data)]);
			}
			data = tmpData.length == 0 ? data : tmpData;


			var previewId = "#freeDataPreview";
			$(previewId + ' table').remove();
			jQuery.jsontotable(data, {
				id: previewId,
				header: true,
				excel: true
			});
			$(previewId + ' table').addClass('stripe');
			$(previewId).parent().show();
		}
		var url;
		var sendData = {
			pageId: pageId,
			code: code
		};
		if (type == 'signValue') {
			url = 'simpleData/getSimpleData';
		} else if (type == 'table') {
			url = 'table/getTable'
		}

		ck.util.sendAjax({
			url: url,
			data: sendData
		}, doSome);
	}


	$('#freeDataPreviewBtn').click(function() {
		var backType = $('input[name="backType"]:checked', $(this).parents('#freeTabSetVal')).val();
		var setVal = $('#setVal').val();
		preview(backType, setVal);
	});


	// 输入值单选按钮事件
	$('#freeTabSetVal input[name="backType"]').bind('change', function() {
		var val = this.value;
		var setPointParent = $('#freeTabSetVal #setPoints').parent();
		if (val == 'table') {
			setPointParent.show();
		} else {
			setPointParent.hide();
		}
	});

	function getRealHtml(freeHtml, hideHtml, insertEle) {
		ck.util.sendAjax({
			url: 'freeTable/getRealTabHtmlByFreeTabHtml',
			data: {
				pageId: pageId,
				freeTabHtml: encodeURIComponent(freeHtml),
				t: new Date().getTime()
			}
		}, function(data) {
			insertCkFreeTableHtml(data.html, hideHtml, insertEle, data.simpleUseArgs);
		});
	}


	var freeTabDialogOk = function() {
		var mergedCellInfos = [];
		if (hot1.mergeCells) {
			mergedCellInfos = hot1.mergeCells.mergedCellInfoCollection.slice(0); // 拷贝
		}

		var data = hot1.getData().slice(0); // 拷贝

		var freeTabs = buildHtml(data, mergedCellInfos);
		var element = $(this).data('element');
		var id = $(this).data('id');

		$('body').data(id, {
			data: freeTabs[1],
			mergedCellInfos: mergedCellInfos,
			cellMetas: freeTabs[2]
		});
		var insertEle = element.findOne('.simplebox-content');
		var findEle = insertEle.getChildren();
		var count = findEle.count();
		if (count > 0) {
			for (var i = 0; i < count; i++) {
				findEle.getItem(0).remove();
			}
		}

		var freeTable = freeTabs[0];
		var hideFreeTab = freeTable.clone().addClass('hideClass').hide();

		getRealHtml(
			freeTable[0].outerHTML,
			hideFreeTab[0].outerHTML,
			insertEle);

		$(this).data('forInit', false);
		$(this).dialog("close");
	}


	$('#freeTableDiv').dialog({
		title: '自定义表格',
		width: 800,
		height: 550,
		modal: true,
		show: true,
		autoOpen: false,
		close: function() {
			var element = $(this).data('element');
			var forInit = $(this).data('forInit');
			if (forInit) {
				element.getParent().remove();
			}
			$(this).removeData('forInit');
		},
		buttons: [{
			text: "确定",
			click: freeTabDialogOk
		}, {
			text: "取消",
			click: function() {
				$(this).dialog("close");
			}
		}]
	});
});

function coverRenderer(instance, td, row, col, prop, value, cellProperties) {
	var classNames = cellProperties.className;
	var $_td = $(td);
	$_td.unbind();
	if (classNames.indexOf('dbFun') >= 0) {
		$_td.on('dblclick', function() {
			var cellMeta = hot1.getCellMeta(row,col);
			var classNames = cellMeta.className;
			if(classNames.indexOf('dbFun')>=0){
				showDbFunDialog(row, col);
			}
		});
	} else if (classNames.indexOf('expression') >= 0) {
		$_td.on('dblclick', function() {
			var code = hot1.getCellMeta(row, col).code;
			if(code && code!=""){
				$('.handsontableInput').val(code);
			}
		});
	}
	td.className = classNames;
	Handsontable.Dom.empty(td);
	return td;
}

function showHandTable(mergeCells, data, cellMetas) {
	var option = {
		colHeight: 24,
		colHeaders: true,
		rowHeaders: true,
		contextMenu: true,
		minSpareRows: 1,
		manualColumnResize: true,
		manualRowResize: true,
		mergeCells:true,
		className: "htCenter htMiddle"
	};

	if (mergeCells) {
		option = $.extend(true, option, {
			mergeCells: mergeCells
		});
	}
	if (data) {
		option = $.extend(true, option, {
			data: data
		});
	} else {
		option = $.extend(true, option, {
			data: data1
		});
	}

	$('#freeTableDiv').children().remove();
	$('#freeTableDiv').append('<div id="handsontable"></div>');
	var $content = document.getElementById("handsontable");
	hot1 = new Handsontable($content, option);

	var $_root = $(hot1.rootElement);

	var areaWidth = 0;

	hot1.addHook('modifyColWidth', function(width, col) {
		if (col == 0)
			areaWidth = 0;
		areaWidth += width;
		var countCols = this.countCols();
		if (col == countCols - 1) {
			var newWidth = (areaWidth + 72) + 'px';
			var oldWidth = $_root.css('width');
			if (newWidth != oldWidth) {
				$_root.css('width', newWidth);
			}
		}
	});

	var areaHeight = 0;
	var defColHeight = hot1.getSettings().colHeight;
	hot1.addHook('afterChange', function(changes, source) {
		var row = changes[0][0],
			col = changes[0][1],
			oldVal = changes[0][2],
			newVal = changes[0][3];
		var $_copyPaste = $('#CopyPasteDiv');

		if (source == 'edit') {
			var cell = hot1.getCell(row, col);
			var $_cell = $(cell);

			// 判断是否为excel函数
			var isFun = newVal.indexOf('=') == 0;
			// 引用系统函数值
			var isSysFun = newVal.indexOf('#') == 0;
			var cellMeta = hot1.getCellMeta(row, col);
			var classNames = cellMeta.className;
			var defClassName = hot1.getSettings().className

			if (isFun) {
				cellMeta.renderer = coverRenderer;
				cellMeta.code = newVal;
				if (classNames.indexOf('expression') == -1) {
					cellMeta.className = defClassName + ' expression';
				}
				hot1.render();
			} else if (isSysFun) {
				if (classNames.indexOf('sysFun') == -1) {
					cellMeta.className = defClassName + ' sysFun';
				}
			} else { //清除数据样式
				cellMeta.className = defClassName;
			}
		} else if (source == 'paste') {
			var copyMeta = $('body').data('copyMeta');
			if (copyMeta) {
				hot1.setCellMetaObject(row, col, copyMeta);
				hot1.render();
			}
		}
	});

	hot1.addHook('beforeKeyDown', function(event) {
		var keyCode = event.keyCode;
		var isCtrlDown = false;
		if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) {
			isCtrlDown = true;
		}
		var selected = this.getSelected();
		if (selected) {
			var startRow = selected[0],
				startCol = selected[1],
				endRow = selected[2],
				endCol = selected[3];
			if (keyCode == 46) { // delete
				if (startRow == endRow && startCol == endCol) { // 至选中一个单元格
					var cellMeta = this.getCellMeta(startRow, startCol);
					cellMeta.className = this.getSettings().className;

					delete cellMeta.code;
					delete cellMeta.backtype;
					cellMeta.readOnly = false;

				}
			} else if (isCtrlDown && (event.keyCode === Handsontable.helper.KEY_CODES.C)) { // ctrl
				var cellMeta = hot1.getCellMeta(startRow, startCol);
				if (cellMeta.readOnly || cellMeta.className.indexOf('expression') >= 0) {
					$('body').data('copyMeta', cellMeta);
				} else {
					$('body').removeData('copyMeta');
				}
			}
		}
	});
	hot1.updateSettings(hotSetting);

	if (cellMetas) {
		for (var i = 0; i < cellMetas.length; i++) {
			var cellMeta = cellMetas[i];
			var col = cellMeta.col,
				row = cellMeta.row,
				rendererName = cellMeta.rendererName;
			if (rendererName) {
				hot1.getCellMeta(row, col).renderer = eval(rendererName);
			}
		}
		for (var i = 0; i < cellMetas.length; i++) {
			var cellMeta = cellMetas[i];
			var col = cellMeta.col,
				row = cellMeta.row,
				code = cellMeta.code,
				backtype = cellMeta.backtype,
				myclass = cellMeta.myclass;
			var hotCellMeta = hot1.getCellMeta(row, col);

			hotCellMeta.code = code;
			if (myclass == 'dbFun') {
				hotCellMeta.backtype = backtype;

				if (backtype == 'table') {
					var points = cellMeta.points;
					hotCellMeta.points = points;
				}
				hot1.getCellMeta(row, col).readOnly = true;
			}

			if (cellMeta.className) {
				hotCellMeta.className = cellMeta.className
			} else if (myclass) {
				hotCellMeta.className = hotCellMeta.className + ' ' + myclass;
			}
		}
	}
}

function buildHtml(data, mergedCellInfos) {
	var otherData = $.extend(true, [], data);

	var table = $('<table></table>');
	// 总行数
	var countRow = hot1.countRows();
	// 总列数
	var countCol = hot1.countCols();

	var cellMetas = [];

	for (var row = 0; row < countRow; row++) {
		var newTr = $('<tr></tr>');
		for (var col = 0; col < countCol; col++) {
			var cellData = hot1.getDataAtCell(row, col);

			var defCellMeta = hot1.getSettings().className;
			var cellMeta = hot1.getCellMeta(row, col);
			var className = cellMeta.className;
			cellData = cellData == undefined ? '' : cellData;
			if (cellData) {
				// 去掉 png 后缀，解决之前版本的遗留问题
				if (cellData.indexOf('png') >= 0) {
					cellData = '';
				}
			} else {
				cellData = '';
			}

			var $cell = $('<td class="' + className + '">' + cellData + '</td>');
			newTr.append($cell);

			var renderer = cellMeta.renderer;
			var code = cellMeta.code;
			var obj;
			if (code) {
				obj = {
					row: row,
					col: col,
					code: code
				}
				if (renderer) {
					var rendererName = renderer.getName();
					obj = $.extend(obj, {
						rendererName: rendererName
					});
				}

				$cell.attr('code', code);
				if ($cell.hasClass('dbFun')) {
					var backtype = cellMeta.backtype;
					$cell.attr('backtype', backtype);

					obj = $.extend(obj, {
						backtype: backtype,
						myclass: 'dbFun'
					});

					if (backtype == 'table') {
						var points = cellMeta.points;
						obj = $.extend(obj, {
							points: points
						});
						$cell.attr('points', points);
					}
				} else if ($cell.hasClass('expression')) {
					obj = $.extend(obj, {
						myclass: 'expression'
					});
				} else if ($cell.hasClass('sysFun')) {
					obj = $.extend(obj, {
						myclass: 'sysFun'
					});
				}
			}

			// 放入修改的对齐样式
			if (defCellMeta != className) {
				if (obj) {
					obj = $.extend(obj, {
						className: className
					});
				} else {
					obj = {
						row: row,
						col: col,
						className: className
					};
				}
			}

			if (obj) {
				cellMetas.push(obj);
				obj = undefined;
			}
		}
		table.append(newTr);
	}

	for (var index = 0; index < mergedCellInfos.length; index++) {
		var mergedCellInfo = mergedCellInfos[index];
		var mRow = mergedCellInfo.row,
			mRowspan = mergedCellInfo.rowspan;
		var mCol = mergedCellInfo.col,
			mColspan = mergedCellInfo.colspan;

		var selectRows = table.find('tr').slice(mRow, (mRowspan + mRow));
		var isFirst = true;
		$.each(selectRows, function(i, n) {
			var $_this = $(n);
			if (isFirst) {
				isFirst = false;
				var needTds = $(n).find('td').slice(mCol, (mCol + mColspan));
				needTds.filter(':first').attr('rowspan', mRowspan).attr('colspan', mColspan).attr('data-col', mColspan - 1).attr('data-type', 'head').css('height', (mRowspan * 24) + 'px');
				needTds.filter(':not(:first)').addClass('delspan');
			} else {
				$(n).find('td').slice(mCol, (mCol + mColspan)).addClass(
					'delspan');

				var findTd = $(n).find('td').slice(mCol - 1, mCol);
				if (findTd.size() > 0) {
					findTd.attr('data-type', 'head');
				} else {
					findTd = $(n).find('td').slice((mCol + mColspan), (mCol + mColspan + 1));
					findTd.attr('data-type', 'bottom');
				}
				findTd.attr('data-col', mColspan);
			}
		});
	}
	table.find('.delspan').hide();

	// 去除png 后缀
	for (var i = 0; i < otherData.length; i++) {
		var datas = otherData[i];
		for (var y = 0; y < datas.length; y++) {
			var d = otherData[i][y];
			if (d && d.indexOf('png') >= 0) {
				d = '';
				otherData[i][y] = d;
			}
		}
	}

	return [table, otherData, cellMetas];
}
